package com.dandelion.commons.log;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dandelion.commons.spring.SpringContextHolder;
import com.dandelion.commons.utils.IpUtil;
import com.dandelion.commons.web.model.AjaxResponse;
import com.dandelion.manager.system.domain.SysLogLogin;
import com.dandelion.manager.system.service.impl.SysLogLoginServiceImpl;

/**
 * 系统日志帮助类
 */
@Component
public class LoginLogHelper {
	private static Logger logger = LogManager.getLogger(LoginLogHelper.class);
	
	/**
	 * 登录日志
	 */
	public static void log(final AjaxResponse ajaxResponse, final String username) {
		HttpServletRequest request = SpringContextHolder.getHttpRequest() ;
		
		String userAgent = request.getHeader("user-agent") ;
		String ip = IpUtil.getRemoteAddr(request) ;
		String description = ajaxResponse.getMessage() ;
		Boolean status = ajaxResponse.getStatus() ;
		logger.info("验证：{}——账号：{}——描述：{}——IP：{}——设备信息：{}", (
				status?"Success":"Failure"), 
				username, 
				description,
				ip, 
				userAgent
		);
		logToDb(ajaxResponse.getStatus(), username, ajaxResponse.getMessage(), ip, userAgent);
	}

	/**
	 * 存储日志到数据库
	 */
	private static void logToDb(final boolean status, final String username, final String description, final String ip, final String device) {
		SysLogLoginServiceImpl sysLogLoginService = SpringContextHolder.getBean(SysLogLoginServiceImpl.class) ;
		
		SysLogLogin sysLog = new SysLogLogin() ;
		sysLog.setUsername(username);
		sysLog.setStatus(status);
		sysLog.setIp(ip);
		sysLog.setDevice(device);
		sysLog.setDescription(description);
		sysLogLoginService.add(sysLog);
		
	}
}
